package com.xxpt.common.utils.amqp.config;

import com.xxpt.common.constant.DelayedQueues;
import com.xxpt.common.constant.Queues;
import com.xxpt.common.utils.amqp.util.RabbitMqUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import java.util.HashMap;
import java.util.Map;

@Slf4j
public class MqConfig {
    @Autowired
    AmqpAdmin amqpAdmin;

    /**
     * 创建队列并绑定交换机
     */
    @Autowired
    public void bindingQueue(@Qualifier("topicExchange") Exchange topicExchange, @Qualifier("dlx") Exchange dlxExchange) {
        for(Queues qu: Queues.values()){
            Map<String, Object> argsMap = new HashMap<>();
            if(StringUtils.isNotBlank(qu.getRoutingKey())) {
                // 先创建死信队列
                Queue dlxQueue = new Queue(qu.getRoutingKey());
                amqpAdmin.declareQueue(dlxQueue);
                Binding dlxBinding = BindingBuilder.bind(dlxQueue).to(dlxExchange).with(qu.getRoutingKey()).noargs();
                amqpAdmin.declareBinding(dlxBinding);
                log.info("声明{}队列并绑定{}交换机，routingKey={}", qu.getName(), dlxExchange.getName(), qu.getRoutingKey());

                // 再声明队列
                argsMap.put("x-dead-letter-exchange", dlxExchange.getName());
                argsMap.put("x-dead-letter-routing-key", qu.getRoutingKey());
            }

            Queue queue = new Queue(qu.getName(), true, false, false, argsMap);
            amqpAdmin.declareQueue(queue);
            Binding isPassQueueBinding = BindingBuilder.bind(queue).to(topicExchange).with(qu.getName()).noargs();
            amqpAdmin.declareBinding(isPassQueueBinding);
            log.info("声明{}队列并绑定{}交换机，routingKey={}", qu.getName(), topicExchange.getName(),qu.getName());
        }
    }

    @Autowired
    public void bindingDelayedQueue(@Qualifier("delayExchange") Exchange delayExchange) {
        for(DelayedQueues qu: DelayedQueues.values()){
            /*Map<String, Object> args = new HashMap<>();
            // 设置类型，可以为fanout、direct、topic
            args.put("x-delayed-type", "direct");
            // 第一个参数是延迟交换机名字，第二个是交换机类型，第三个设置持久化，第四个设置自动删除，第五个放参数
            CustomExchange exchange = new CustomExchange(RabbitMqUtil.EXCHANGE_DELAYED_DIRECT,"x-delayed-message", true,false, args);
*/
            Queue queue = new Queue(qu.getName(), true, false, false);
            amqpAdmin.declareQueue(queue);
            Binding binding = BindingBuilder.bind(queue).to(delayExchange).with(qu.getRoutingKey()).noargs();
            amqpAdmin.declareBinding(binding);
            log.info("声明{}队列并绑定{}延迟交换机，routingKey={}", qu.getName(), RabbitMqUtil.EXCHANGE_DELAYED_DIRECT, qu.getRoutingKey());
        }
    }
}
